package com.raorao.config.service.register;

import com.raorao.config.common.serializer.ZookeeperSerializer;
import com.raorao.config.config.ConfigProperty;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author raorao
 * @version 1.0
 * @description: Zookeeper服务注册器
 * @date 2021/11/26 17:05
 */
@Service
public class ZookeeperServiceRegister implements ServiceRegister{

    /**
     * Zk客户端
     */
    private ZkClient client;

    public ZookeeperServiceRegister(ConfigProperty configProperty){
        client = new ZkClient(configProperty.getAddress());
        client.setZkSerializer(new ZookeeperSerializer());
    }

    @Override
    public Boolean save(String path, String data) {
        String servicePath = path;
        if (!client.exists(servicePath)) {
            //创建持久化节点，true表示如果父节点不存在则创建父节点
            client.createPersistent(servicePath, true);
        }
//        client.create(servicePath, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        client.writeData(servicePath, data);
        return Boolean.TRUE;
    }

    @Override
    public Boolean delete(String path) {
        this.deleteChild(path);
        return Boolean.TRUE;
    }

    private void deleteChild(String path){
        if (!client.exists(path)){
            return;
        }
        //遍历节点 是否存在子节点 参数1 节点路径 参数2 是否监控
        List<String> list = client.getChildren(path);
        //如果存在 调用自己删除
        if(list != null&& list.size()>0){
            for(String node :list){
                deleteChild(path+"/"+node);
            }
        }
        client.delete(path,-1); //删除节点
    }
}
